package demo;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Calendar;
import java.util.List;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.HtmlButtonInput;
import com.gargoylesoftware.htmlunit.html.HtmlCheckBoxInput;
import com.gargoylesoftware.htmlunit.html.HtmlDivision;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSpan;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import com.gargoylesoftware.htmlunit.util.Cookie;

public class LBSPage {

  private final static String BAIDU_LBS_URL = "http://api.map.baidu.com/lbsapi/getpoint/";

  public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException, InterruptedException {
    long start = System.currentTimeMillis();
    WebClient webclient = new WebClient(BrowserVersion.CHROME);
    final HtmlPage htmlpage = webclient.getPage(BAIDU_LBS_URL);
    webclient.getOptions().setCssEnabled(false);
    webclient.getOptions().setJavaScriptEnabled(true);
    webclient.waitForBackgroundJavaScript(1000 * 5);
    webclient.getOptions().setThrowExceptionOnScriptError(false);
    webclient.getOptions().setThrowExceptionOnFailingStatusCode(false);
    webclient.setAjaxController(new NicelyResynchronizingAjaxController());
    webclient.getCookieManager().setCookiesEnabled(true);
    CookieManager cookieManager = new CookieManager();
    cookieManager.addCookie(new Cookie(".baidu.com", "BAIDUID", "91C1B82585C704AFC75F870046E70BEF:FG=1"));
    cookieManager.addCookie(new Cookie(".baidu.com", "BIDUPSID", "AFBF9166BC02D0FD8A4794AF2A9FF767"));
    webclient.setCookieManager(cookieManager);

    String keyword = "青岛杨扁担";

    final HtmlTextInput textFiled = (HtmlTextInput) htmlpage.getFirstByXPath("//input[@id=\"localvalue\"]");
    // 为了提供搜索结果的准确性，请将城市区域添加到关键词中！
    textFiled.setValueAttribute(keyword);
    final HtmlCheckBoxInput checkButton = (HtmlCheckBoxInput) htmlpage.getFirstByXPath("//input[@id=\"pointLabel\"]");
    checkButton.setChecked(false);
    final HtmlButtonInput submit = (HtmlButtonInput) htmlpage.getFirstByXPath("//input[@id=\"localsearch\"]");

    final HtmlPage resultPage = submit.click();
    final HtmlSpan resultNum = (HtmlSpan) resultPage.getFirstByXPath("//span[@id=\"resultNum\"]");
    // 通过submit.click处理类似ajax的非form请求需求对请求相应进行判断
    for (int i = 1; i <= 20; i++) {
      if (!"".equals(resultNum.asText())) {
        System.out.println("Result parsed done! retry count = " + i);
        break;
      }
      synchronized (resultPage) {
        resultPage.wait(500);
        System.out.println("Wait for, retry count = " + i);
      }
    }
    final HtmlDivision txtPanel = (HtmlDivision) resultPage.getFirstByXPath("//div[@id=\"txtPanel\"]");
    final List<?> resultMap = txtPanel.getByXPath("//div[starts-with(@id, 'no_')]");
    for (int i = 0; i < resultMap.size(); i++) {
      /*
       * HtmlDivision的getFirstByXPath存在BUG！通过resultDiv中筛选子标签，竟然还会从parent层获取！ HtmlDivision resultDiv
       * = (HtmlDivision) txtPanel.getFirstByXPath("//div[@id=\"no_" + i + "\"]");
       * System.out.println(resultDiv.asXml());
       */
      // 备注：搜索结果仅限第一页（最多10个值）。
      System.out.println("------ 第" + (i + 1) + "个查询结果 ------");
      StringBuffer sb = new StringBuffer();
      sb.append("{name:'" + ((DomNode) txtPanel.getFirstByXPath("//div[@id=\"no_" + i + "\"]/a[@href=\"javascript:void(0)\" and @title]")).getTextContent() + "',");
      String tmp =
          ((DomNode) txtPanel.getFirstByXPath("//div[@id=\"no_" + i + "\"]/p")).getTextContent().replaceAll("\t\t", "',").replaceAll("：", ":'").replaceAll("地址", "address")
              .replaceAll("电话", "mobile").replace("坐标", "loc").trim();
      sb.append(tmp);
      // 记录获取日期/时间戳
      sb.append("updated:" + Calendar.getInstance().getTimeInMillis());
      sb.append("}");
      System.out.println(sb.toString());
    }
    webclient.closeAllWindows();
    long end = System.currentTimeMillis();
    System.out.println(":: > " + BAIDU_LBS_URL + " : took " + (end - start) + " milliseconds ::");
  }
}
